package net.kts.main;

import net.kts.attraction.search.AttractionSearch;
import net.kts.define.SQLiteDatabaseStr;
import net.kts.help.HelpLayout;
import net.kts.help.HelpPreferences;
import net.kts.help.HelpService;
import net.kts.location.MyLocation;
import net.kts.location.MyLocationManager;
import net.kts.placebook.venue.NearbyVenues;
import net.kts.setting.EditPreferences;
import net.kts.setting.language.LanguageUtil;
import net.kts.story.Story;
import net.kts.story.progress.StoryProgressDialog;
import net.kts.subskill.SubSkill;
import net.kts.transrate.TranslateService;
import net.kts.util.network.NetworkCheck;
import net.kts.util.sqlite.MoveDatabase;
import net.kts.util.url.RequestURL;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class KoreaTravelStoryActivity extends TabActivity {
	private static final int EDIT_ID = Menu.FIRST+2;
	private static final int CLOSE_ID = Menu.FIRST+4;
	private static final int HELP_ID = Menu.FIRST+6;
	private static TabHost tabHost;
	private int selectIndex;
	private Activity self;
	private Animation loadAnimation;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.self = this;
        setContentView(R.layout.main);
        
        createLogoLayout();
        checkInternet();
        settingLanquage();
        checkAgreedPostion();
        StoryProgressDialog.setActivity(this);
        HelpPreferences.setHelpPreferences(this);
        sqliteDatabaseInit();
        createMyLocation();        
        
        
        Log.d("kts", "KTS Main Tap onCreate");
        loadAnimation = AnimationUtils.loadAnimation(this, R.anim.story_menu_btn);
        Resources res = getResources();
        KoreaTravelStoryActivity.tabHost = getTabHost();
        TabHost.TabSpec spec;
        Intent intent;
        View tabView;
        
        
        tabView = createTabLayout("search",  R.drawable.main_after_search);
        intent = new Intent(this, AttractionSearch.class);
        spec = tabHost.newTabSpec("Attraction").setIndicator(tabView)
        		.setContent(intent);
        tabHost.addTab(spec);


        tabView = createTabLayout("story",  R.drawable.main_before_story);
        intent = new Intent(this, Story.class);
        spec = tabHost.newTabSpec("Story").setIndicator(tabView)
        		.setContent(intent);
        tabHost.addTab(spec);
        
        tabView = createTabLayout("placebook",  R.drawable.main_before_placebook);
        intent = new Intent(this, NearbyVenues.class);
        spec = tabHost.newTabSpec("PlaceBook").setIndicator(tabView)
        		.setContent(intent);
        tabHost.addTab(spec);
        
        tabView = createTabLayout("more",  R.drawable.main_before_more);
        intent = new Intent(this, SubSkill.class);
        spec = tabHost.newTabSpec("SubSkill").setIndicator(tabView)
        		.setContent(intent);
        tabHost.addTab(spec);
        
        createTabIndex(tabHost);
        tabHost.setCurrentTab(0);
        
        new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				 if(HelpPreferences.isShowing())
				        new HelpService(self)
				        		.add(new HelpLayout(R.drawable.help_main))
				        		.addHelpLayout(new HelpLayout(R.drawable.help_main2));
			}
		}, 1800);
    }


	private void checkAgreedPostion() {
		final SharedPreferences sharedPreferences = getSharedPreferences("AgreedPostion", Activity.MODE_PRIVATE);
        boolean agree = sharedPreferences.getBoolean("agree", false);
        if(!agree){
	        AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
	    	alt_bld.setMessage(TranslateService.translate("[KoreaTravelStory]에서 현재 위치 정보를 사용하고자 합니다. 동의하시겠습니까?"))
	    	.setCancelable(
	    		false).setPositiveButton("Yes",
	    		new DialogInterface.OnClickListener() {
	    		public void onClick(DialogInterface dialog, int id) {
	    			Editor edit = sharedPreferences.edit();
	    			edit.putBoolean("agree", true);
	    			edit.commit();
	    		}
	    		}).setNegativeButton("No",
	    		new DialogInterface.OnClickListener() {
	    		public void onClick(DialogInterface dialog, int id) {
	    			moveTaskToBack(true);
					android.os.Process.killProcess(android.os.Process.myPid());
	    		}
	    		});
	    	AlertDialog alert = alt_bld.create();
	    	alert.setIcon(R.drawable.icon);
	    	alert.show();
        }
	}


	private void createLogoLayout() {
		LayoutInflater inflater = getLayoutInflater();
		final View logoView = (View) inflater.inflate(R.layout.main_logo, null);
		logoView.setBackgroundDrawable(getResources().getDrawable(R.drawable.main_logo));
		addContentView(logoView, new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.FILL_PARENT));
		logoView.setVisibility(logoView.INVISIBLE);
		logoView.startAnimation(AnimationUtils.loadAnimation(this, R.anim.logo));
	}


	private View createTabLayout(String title, int drawble) {
		View view = View.inflate(this, R.layout.main_tab, null);
        ImageView iconView = (ImageView) view.findViewById(R.id.icon);
        TextView titleView = (TextView) view.findViewById(R.id.title);
		iconView.setImageDrawable(getResources().getDrawable(drawble));
		titleView.setText(title);
		return view;
	}

	private void createTabIndex(final TabHost tabHost) {
		final int[] previousIconList = new int[4];
		previousIconList[0] = R.drawable.main_before_search;
		previousIconList[1] = R.drawable.main_before_story;
		previousIconList[2] = R.drawable.main_before_placebook;
		previousIconList[3] = R.drawable.main_before_more;
        
        tabHost.setOnTabChangedListener(new OnTabChangeListener() {
			@Override
			public void onTabChanged(String tabId) {
            	if(tabId.equals("Attraction")){
            		updateTabIcon(previousIconList[selectIndex]);
            		selectIndex = 0;
            		updateTabIcon(R.drawable.main_after_search);
            		startTabAnimation();
            	}else if(tabId.equals("Story")){
            		updateTabIcon(previousIconList[selectIndex]);
            		selectIndex = 1;
            		updateTabIcon(R.drawable.main_after_story);
            		startTabAnimation();
            	}else if(tabId.equals("PlaceBook")){
            		updateTabIcon(previousIconList[selectIndex]);
            		selectIndex = 2;
            		updateTabIcon(R.drawable.main_after_placebook);
            		startTabAnimation();
            	}else if(tabId.equals("SubSkill")){
            		updateTabIcon(previousIconList[selectIndex]);
            		selectIndex = 3;
            		updateTabIcon(R.drawable.main_after_more);
            		startTabAnimation();
            	}
            }

			private void startTabAnimation() {
				ImageView background = (ImageView) getTabHost().getTabWidget().getChildAt(selectIndex).findViewById(R.id.background);
				background.startAnimation(loadAnimation);
			}
        });
	}

	private void createMyLocation() {
		MyLocation myLocation = new MyLocation(self);
		MyLocationManager.setMyLocation(myLocation);
	}
    
    private void updateTabIcon(int iconID) {
    	ImageView iv = (ImageView) getTabHost().getTabWidget().getChildAt(selectIndex).findViewById(R.id.icon);
		iv.setImageDrawable(getResources().getDrawable(iconID));
	}

	private void settingLanquage() {
		LanguageUtil.createLanquage(this);
	}
    
    private void sqliteDatabaseInit() {
    	MoveDatabase moveDatabase = new MoveDatabase(this, SQLiteDatabaseStr.pakageName, SQLiteDatabaseStr.dbFileName, SQLiteDatabaseStr.assertPath);
    	moveDatabase.assertToData();
    }
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE, EDIT_ID, Menu.NONE, "Setting")
				.setIcon(R.drawable.main_preferences)
				.setAlphabeticShortcut('e');
		
		menu.add(Menu.NONE, CLOSE_ID, Menu.NONE, "Close")
				.setIcon(R.drawable.main_close)
				.setAlphabeticShortcut('c');
		
		menu.add(Menu.NONE, HELP_ID, Menu.NONE, "Help on/off")
			.setIcon(R.drawable.main_help);
//			.setAlphabeticShortcut('c');
		
		return(super.onCreateOptionsMenu(menu));
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case EDIT_ID:
				startActivity(new Intent(this, EditPreferences.class));
				return(true);
			case CLOSE_ID:
				//
				// 죽어라!
				moveTaskToBack(true);
				android.os.Process.killProcess(android.os.Process.myPid());
//				ActivityManager am  = (ActivityManager)getSystemService(Activity.ACTIVITY_SERVICE);
//			    am.restartPackage(getPackageName());
//			    finish();
				return(true);
			case HELP_ID:
				if(HelpPreferences.isShowing()){
					HelpPreferences.off();
					Toast.makeText(this, TranslateService.translateRepository("도움말 끄기"), Toast.LENGTH_SHORT).show();
				}else{
					HelpPreferences.on();
					Toast.makeText(this, TranslateService.translateRepository("도움말 켜기"), Toast.LENGTH_SHORT).show();
				}
					
				return(true);
		}
		return(super.onOptionsItemSelected(item));
	}
	
	private boolean checkInternet() {
		// TODO Auto-generated method stub
		int mode =  NetworkCheck.check(this);
		//		03-04 14:37:49.404: I/ActivityManager(107): Displayed com.android.settings/.WirelessSettings: +311ms
		
        try {
        	RequestURL.requestYahooAddress("seoul");
        	showCheckInternet(mode);
		} catch (Exception e) {
			showCheckInternet(2);
			return false;
		}
		return true;
	}


	private void showCheckInternet(int mode) {
		if(mode == 2) {
			AlertDialog.Builder ab = new AlertDialog.Builder(this);
			ab.setCancelable(false);
			ab.setMessage("Internet settings are not. Would you like to set?");
			
			
			ab.setPositiveButton("YES", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					startActivity(new Intent(Settings.ACTION_SETTINGS));
					checkInternet();
				}
			});

			ab.setNegativeButton("NO", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					moveTaskToBack(true);
					android.os.Process.killProcess(android.os.Process.myPid());
				}
			});
			ab.show();
		}
	}
	
	public static void setCurrentTab(int index){
		KoreaTravelStoryActivity.tabHost.setCurrentTab(index);
	}
	
}